from configparser import ConfigParser
import os
import pymysql
from traceback import print_exc

class ReadConf:
    def __init__(self,file):
        self.config = ConfigParser()
        path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(path,encoding="utf-8")

    def get_option(self,option):
        for section in self.config.sections():
            if self.config.has_option(section, option):
                return self.config.get(section, option)
class DB:
    def __init__(self,database):
        self.database = database
        r = ReadConf(str(database) + ".ini")
        self.host = r.get_option(database + "_host")
        self.user = r.get_option(database + "_user")
        self.password = r.get_option(database + "_passwd")

    def connect(self):
        self.db = pymysql.connect(host=self.host,user=self.user,password=self.password,database=self.database,cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            print_exc()
        finally:
            self.close()

    def searchAll(self, sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            print_exc()
        finally:
            self.close()

    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            print_exc()
        finally:
            self.close()
    def insert(self,sql):
        self.__edit(sql)
    def delete(self,sql):
        self.__edit(sql)
    def update(self,sql):
        self.__edit(sql)


